<template>
  <el-date-picker
    v-model="values"
    :range-separator="rangeSeparator"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    :format="format"
    :clearable="clearable"
    :value-format="valueFormat"
    :type="type"
    :size="size"
    :disabled="disabled"
    :picker-options="pickerOptions"
    :default-time="formatDefaultTime(defaultTime, type)"
    :style="{ width: width }"
    @change="handleData"
  />
</template>

<script>

import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  toRefs,
  watch
} from 'vue'

import { getStoreFromInstance } from '@/utils/instance'

export default defineComponent({
  name: 'DatePicker',
  props: {
    value: {
      type: [String, Number, Date, Array],
      default: ''
    },
    format: {
      type: String,
      default: 'yyyy-MM-dd'
    },
    valueFormat: {
      type: String,
      default: 'yyyy-MM-dd'
    },
    //类型
    type: {
      type: String,
      default: 'date'
    },
    size: {
      type: String,
      default: 'small'
    },
    //宽
    width: {
      type: String,
      default: ''
    },
    //默认时间
    defaultTime: {
      type: [Array, String],
      default: null
    },
    //日期选择器中间的文字
    rangeSeparator: {
      type: String,
      default: '至'
    },
    //是否显示清楚按钮
    clearable: {
      type: Boolean,
      default: false
    },
    //是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否限制选择区间
    selectInterval: Boolean
  },
  emits: ['input'],
  setup(props, { emit }) {
    const state = reactive({
      //日期选择器条件：只能选今天及以前的
      pickerOptions: {},
      values: ''
    })

    const store = getStoreFromInstance()

    //const patCur = computed(() => store.getters.patCur)

    const isHistory = computed(() => store.getters.isHistory)

    function handleData() {
      emit('input', state.values)
    }

    // 改变选择区间
    function handleSection(startTime, endTime = Date.now()) {
      state.pickerOptions = {
        disabledDate(time) {
          if (startTime) {
            const isN =
              startTime >= startOfDay(startTime).getTime() + 1000 &&
              startTime <= startOfDay(startTime).getTime() + 8 * 60 * 60 * 1000
            let start = startOfDay(startTime).getTime()
            if (isN) {
              start -= 24 * 60 * 60 * 1000
            }
            return (
              formatDateStamp(time) > formatDateStamp(endTime) ||
              formatDateStamp(time) < start
            )
          }
          return (
            formatDateStamp(time) > formatDateStamp(endTime) ||
            formatDateStamp(time) < formatDateStamp(startTime)
          )
        }
      }

      // 将日期格式化成去时间点
      function formatDateStamp(value) {
        const data = new Date(value),
          year = data.getFullYear(),
          month = (data.getMonth() + 1).toString().padStart(2, 0),
          day = data.getDate().toString().padStart(2, 0)
        return Date.parse(`${year}-${month}-${day} 00:00:00`)
      }
    }

    function formatDefaultTime(n, type) {
      if (n) {
        return n
      }
      if (type === 'date' || type == 'datetime') {
        return '00:00:00'
      }
      return ['00:00:00']
    }

    watch(
      () => props.value,
      val => {
        if (
          val &&
          val.length > 0 &&
          val[0] == undefined &&
          val[1] == undefined
        ) {
          val = ''
        }
        state.values = val
      },
      { immediate: true }
    )

    // watch(
    //   patCur,
    //   val => {
    //     if (props.selectInterval && val) {
    //       handleSection(patCur.value.startRkTime, patCur.value.endCkTime || '')
    //     } else {
    //       handleSection()
    //     }
    //   },
    //   { immediate: true }
    // )

    onMounted(() => {
      if (props.value) {
        state.values = props.value
      }
      if (
        (props.type == 'daterange' || props.type == 'datetimerange') &&
        !isHistory.value
      ) {
        //快捷选择
        state.pickerOptions.shortcuts = [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    })

    return {
      ...toRefs(state),
      handleSection,
      formatDefaultTime,
      handleData
    }
  }
})
</script>
